package com.ctg.behavior.calc.impala.transfer.property;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.utils.CtCalcPropertyUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcPropertyType;
import com.ctg.behavior.common.consts.CtPropertyConsts;
import com.ctg.behavior.common.properties.CtUserPropertiesCalcBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUserPropertiesTransfer implements CtSQLTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtUserPropertiesCalcBody)) {
			log.warn("calcObject is not CtUserPropertiesCalcBody, class={}", calcObject.getClass());
			return "";
		}
		CtUserPropertiesCalcBody calcBody = (CtUserPropertiesCalcBody) calcObject;
		log.info("CtUserPropertiesCalcBody={}", JSON.toJSONString(calcBody));

		String appId = calcBody.getAppId();

		// 组装SQL
		StringBuilder impalaSQL = new StringBuilder();
		impalaSQL.append(" SELECT DISTINCT ");
		impalaSQL.append(" user_id AS userId ");
		// impalaSQL.append(" , device_id AS deviceId ");
		for(String field : calcBody.getProfiles()) {
			CtCalcPropertyType pType = CtCalcPropertyUtils.getValueType(field);
			if(!CtPropertyConsts.PROPERTY_USER.equals(pType.getType())){
				continue;
			}
			impalaSQL.append(" , ").append(pType.getProperty()).append(" AS ").append(pType.getProperty()).append(" ");
		}
		
		impalaSQL.append(" FROM a_user_kudu_").append(appId);
		impalaSQL.append(" WHERE 1=1 ");
		
		impalaSQL.append(" AND user_id = '").append(calcBody.getUserId()).append("' ");
		// impalaSQL.append(" AND device_id = '").append(calcBody.getDeviceId()).append("' ");

		impalaSQL.append(" LIMIT 1 ");

		return impalaSQL.toString();
	}

}
